package com.yckj.web.uol.filter; /**
 * @Classname ${NAME}
 * @Description TODO
 * @Copyright:Copyright(c) 2021
 * @Company 英才汇硕信息科技有限公司
 * @Author xu
 * @Version 1.0
 * @Date 2021/7/29 9:01
 */

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


public class EncondingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //对响应进行编码处理
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        chain.doFilter(new MyRequest(request), response);

}
}
//装饰者模式
class  MyRequest extends HttpServletRequestWrapper {
    private  HttpServletRequest request;
    public MyRequest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }
    //重写getParameter对方法进行加强
    @Override
    public String getParameter(String name){
        String method = request.getMethod();
        if ("post".equalsIgnoreCase(method)){
            try {
                request.setCharacterEncoding("utf-8");
                return request.getParameter(name);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return super.getParameter(name);
    }
}
